<div class="row-fluid clearfix">
    <div class="col-md-12 column">
        <ul class="breadcrumb">
            <li>
                <a href="index.html">首页</a>
            </li>
            <li class="active">
                角色管理
            </li>
        </ul>
    </div>
    <div class="col-md-12 column">
        <div class="col-sm-6 div-page">
            <div class="col-sm-12 div-table">
                <div id="custom-toolbar">

                </div>
                <table id="table" class="table table-hover table-condensed" data-toolbar="#custom-toolbar"
                       data-click-to-select="true" data-single-select="true" data-height="450">
                    <thead>
                    <tr>
                        <th data-field="state" data-checkbox="true"></th>
                        <th data-field="Role_name" data-halign="left" data-align="left">角色名</th>
                        <th data-field="Role_Level_name" data-halign="left" data-align="left">机构级别</th>
                        <th data-field="Role_sort" data-halign="left" data-align="left">排序</th>
                    </tr>
                    </thead>
                </table>
            </div>
        </div>
        <div class="col-sm-6 div-page">
            <div class="col-sm-12 div-table">
                <div id="custom-toolbar_right">
                    <div class="form-inline" role="form">
                        <button id="btn-DataSave" type="button" role="button" class="btn btn-sm btn-Data btn-info disabled">
                            <span class="glyphicon glyphicon-th-list"></span> 保存</button>
                    </div>
                </div>
                <table id="table1" class="table table-hover table-condensed" data-toolbar="#custom-toolbar_right"
                       data-click-to-select="true"  data-height="450">
                    <thead>
                    <tr>
                        <th data-field="state" data-checkbox="true"></th>
                        <th data-field="Mpi_nameTree" data-halign="left" data-align="left">菜单名</th>
                        <th data-field="Mpi_typeShow" data-halign="left" data-align="left" data-sortable="true">类型</th>
                    </tr>
                    </thead>
                </table>
            </div>
        </div>
        <div class="col-sm-12 alert alert-success div-alert" id="events-result" data-es="Aquí se muestra el resultado del evento"></div>
        <!-- #遮罩层 --->
        <div class="modal fade" id="modal-DataEdit" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                        <div class="modal-title" id="myModalLabel">
                            角色管理
                        </div>
                    </div>
                    <form id="validForm" name="validForm" method="post" class="form-horizontal layer_msg">
                        <input type="hidden" data-field="actionType" id="actionType" name="actionType" />
                        <input type="hidden" data-field="Role_id" id="Role_id" name="Role_id" />

                        <div class="modal-body">
                            <div class="form-group">
                                <label class="col-sm-3 control-label">角色名</label>
                                <div class="form-group col-sm-6">
                                    <input type="text" class="form-control" id="Role_name" name="Role_name" placeholder="角色名"
                                           required  data-fv-notempty-message="请输入" />
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-3 control-label">机构级别</label>
                                <div class="form-group col-sm-6">
                                    <input type="hidden" class="form-control" id="Role_Level_name" name="Role_Level_name" />
                                    <select class="form-control" data-fv-notempty data-fv-notempty-message="机构级别" id="Role_Level" name="Role_Level" onchange="">

                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-3 control-label">角色类型</label>
                                <div class="form-group col-sm-6">
                                    <input type="hidden" class="form-control" id="Role_typeShow" name="Role_typeShow" />
                                    <select class="form-control" data-fv-notempty data-fv-notempty-message="角色类型" id="Role_type" name="Role_type" onchange="">

                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-3 control-label">通用操作权限</label>
                                <div class="form-group col-sm-9">
                                    <div class="checkbox">
                                        <label>
                                            <input type="checkbox" name="CustomerAction" value="CommonDataAdd" /> 新增
                                        </label>
                                        <label>
                                            <input type="checkbox" name="CustomerAction" value="CommonDataModify" /> 修改
                                        </label>
                                        <label>
                                            <input type="checkbox" name="CustomerAction" value="CommonDataCancel" /> 删除
                                        </label>
                                        <label>
                                            <input type="checkbox" name="CustomerAction" value="CommonDataReset" /> 操作员密码重置
                                        </label>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-3 control-label">客户操作权限</label>
                                <div class="form-group col-sm-9">
                                    <div class="checkbox">
                                        <!--<label>
                                            <input type="checkbox" name="CustomerAction" value="DataAdd" /> 开户</label>-->
                                        <label>
                                            <input type="checkbox" name="CustomerAction" value="DataModify" /> 修改
                                        </label>
                                        <label>
                                            <input type="checkbox" name="CustomerAction" value="DataConfirm" /> 复核
                                        </label>
                                        <!--<label>
                                            <input type="checkbox" name="CustomerAction" value="DataCancel" /> 销户
                                        </label>-->
                                        <label>
                                            <input type="checkbox" name="CustomerAction" value="DataReplace" /> 更换
                                        </label>
                                        <label>
                                            <input type="checkbox" name="CustomerAction" value="DataUnbind" /> 解绑
                                        </label>

                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-3 control-label">排序</label>
                                <div class="form-group col-sm-6">
                                    <input type="text" class="form-control" id="Role_sort" name="Role_sort" placeholder="排序"
                                            />
                                </div>
                            </div>
                            <div class="form-group hidden">
                                <label class="col-sm-3 control-label">备注</label>
                                <div class="form-group col-sm-9">
                                    <input type="text" class="form-control" id="Role_note" name="Role_note" placeholder="备注"
                                            />
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button id="modal-btn-save" type="submit" class="btn btn-primary">保存</button>
                            <button id="modal-btn-del" type="button" class="btn btn-danger">确认删除</button>
                            <button id="modal-btn-close" type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

    </div>
</div>

<script>
    $(function () {

        var btnHtml ;
        var btnRole = JSON.parse($.cookie("Role_note"));

        btnHtml = '<div class="form-inline" role="form">';
        btnHtml += (btnRole["CommonDataAdd"] || $.cookie("Custom-Auth-Name") == "0000000000") ? '<button id="btn-CommonDataAdd"  type="button" role="button" class="btn btn-sm btn-primary">' +
                '<span class="glyphicon glyphicon-plus"></span> 新增</button> ' : '' ;
        btnHtml += (btnRole["CommonDataModify"] || $.cookie("Custom-Auth-Name") == "0000000000") ? '<button id="btn-CommonDataModify" type="button" role="button" class="btn btn-sm btn-Data btn-success disabled">' +
                '<span class="glyphicon glyphicon-pencil"></span> 修改</button> ' : '' ;
        btnHtml += (btnRole["CommonDataCancel"] || $.cookie("Custom-Auth-Name") == "0000000000") ? '<button id="btn-CommonDataCancel"  type="button" role="button" class="btn btn-sm btn-Data btn-danger disabled" >' +
                '<span class="glyphicon glyphicon-trash"></span> 删除</button> ' : '' ;

        $("#custom-toolbar").append(btnHtml);

        ///左侧
        $('#table').bootstrapTable({
            url: globalUrl+'api/Role',
            responseHandler:function(resp){
                return resp.data.rows;
            },
            pagination:false,
            search:true
        })
                .on('click-row.bs.table', function (e, row, $element) {
                    //$("#events-result").text('Event: click-row.bs.table, data: ' + JSON.stringify(row));
                    /* by lichun 切换选中颜色*/
                    if ( $element.hasClass('selected') ) {
                        $element.removeClass('info');
                    }
                    else {
                        $element.parent('tbody').find(' > tr.selected ').removeClass("info");
                        $element.addClass('info');
                    }
                })
                .on('check.bs.table', function (e, row, $element) {
                    //$("#events-result").text('Event: check.bs.table, data: ' + JSON.stringify(row));
                    $(".btn-Data").removeClass("disabled");
                    loadRoleSelected(row.Role_id);
                })
                .on('uncheck.bs.table', function (e, row, $element) {
                    //$("#events-result").text('Event: uncheck.bs.table, data: ' + JSON.stringify(row));
                    $(".btn-Data").addClass("disabled");
                    removeRoleSelected();
                });


        ///右侧

        $('#table1').bootstrapTable({
            url: globalUrl+'api/Menu',
            responseHandler:function(resp){
                var dataSet=[];
                //alert(JSON.stringify(resp.data));
                var data = resp.data[0].children;
                GetTreeMenuData(dataSet,0,data);
                //alert(JSON.stringify(dataSet));
                return dataSet;
            },
            pagination:false,
            search:false
        })
                .on('click-row.bs.table', function (e, row, $element) {
                    //$("#events-result").text('Event: click-row.bs.table, data: ' + JSON.stringify(row));
                })
                .on('dbl-click-row.bs.table', function (e, row, $element) {
                    //$("#events-result").text('Event: dbl-click-row.bs.table, data: ' + JSON.stringify(row));
                })
                .on('check.bs.table', function (e, row) {
                    //$("#events-result").text('Event: check.bs.table, data: ' + JSON.stringify(row));
                    refreshCheckSelected(row);
                })
                .on('uncheck.bs.table', function (e, row) {
                    //$("#events-result").text('Event: uncheck.bs.table, data: ' + JSON.stringify(row));
                    refreshCheckSelected(row);
                })

        $("#Role_Level").change(function(){
            refreshSelectShow($("#Role_Level"),$("#Role_Level_name"));
        });
        $("#Role_type").change(function(){
            refreshSelectShow($("#Role_type"),$("#Role_typeShow"));
        });

        /*筛选框下拉列表初始化_add_ywq_20140123-Start*/
        FormatSelect(globalUrl+"api/Dict?Typeid=0000000002",$("#Role_Level"),"请选择","",function(resp){});
        FormatSelect(globalUrl+"api/Dict?Typeid=0000000001",$("#Role_type"),"请选择","",function(resp){});
        /*筛选框下拉列表初始化_add_ywq_20140123-End*/

        ///弹出层验证，submit时生效
        $('#validForm')
            .formValidation()
            .on('success.form.fv', function(e) {
                e.preventDefault();
                var $form = $(e.target);
                var bv = $form.data('formValidation');
                if($('#validForm').find(' input[name="actionType"] ').val()=="edit"){
                    // Use Ajax to submit form data
                    $.ajax({
                        data:$form.serializeArray(),
                        type: "put",
                        url: globalUrl+"api/Role",
                        dataType: "json",
                        success: function (resp) {
                            if(resp.result)
                            {
                                //$("#events-result").text('Send data: ' + $form.serialize());
                                dataBindToTable($('#table'),$('#validForm'));
                                //关闭弹出窗口
                                $('#modal-DataEdit').modal('hide');
                            }
                            else
                            {
                                alert(resp.msg);
                            }
                        },
                        error:function(){
                            alert("更新数据失败！");
                        }
                    });
                }else if($('#validForm').find(' input[name="actionType"] ').val()=="add"){
                    // Use Ajax to submit form data
                    $.ajax({
                        data:$form.serializeArray(),
                        type: "post",
                        url: globalUrl+"api/Role",
                        dataType: "json",
                        success: function (resp) {
                            if(resp.result)
                            {
                                $("#Role_id").val(resp.msg);
                                //$("#events-result").text('Send data: ' + $form.serialize());
                                dataAddToTable($('#table'),$('#validForm'));
                                //关闭弹出窗口
                                $('#modal-DataEdit').modal('hide');
                            }
                            else
                            {
                                alert(resp.msg);
                            }
                        },
                        error:function(){
                            alert("更新数据失败！");
                        }
                    });
                }else{

                }

            });
    });
    ///表格事件/////////////////////////////////////////////////////

    //新增按钮
    $('#btn-CommonDataAdd').on("click",function () {
        //$("#events-result").text('Selected values: ' + JSON.stringify($('#validForm').serializeArray()));
        dataBindToModal($('#validForm'),null);
        SetSelectSelected($("#Role_Level"),$("#Role_Level").val());
        SetSelectSelected($("#Role_type"),$("#Role_type").val());
        formatCustomerAction($('#validForm'),'Role_note','CustomerAction');
        $('#modal-btn-del').addClass('hidden');
        $('#modal-btn-save').removeClass('hidden');
        $('#validForm').find(' input[name="TransVersion"]').val("1");
        $('#validForm').find(' input[name="actionType"] ').val("add");
        $('#modal-DataEdit').modal('show');
    });
    //编辑按钮数据传递
    $('#btn-CommonDataModify').on("click",function () {
        dataBindToModal($('#validForm'),$('#table'));
        SetSelectSelected($("#Role_Level"),$("#Role_Level").val());
        SetSelectSelected($("#Role_type"),$("#Role_type").val());
        formatCustomerAction($('#validForm'),'Role_note','CustomerAction');
        //$("#events-result").text('Selected values: ' + JSON.stringify($('#validForm').serializeArray()));

        //objFormatReadonly($('#validForm'),['TransCode']);
        $('#modal-btn-del').addClass('hidden');
        $('#modal-btn-save').removeClass('hidden');
        $('#validForm').find(' input[name="actionType"] ').val("edit");
        $('#modal-DataEdit').modal('show');
    });
    //删除按钮
    $('#btn-CommonDataCancel').on("click",function () {

        dataBindToModal($('#validForm'),$('#table'));
        SetSelectSelected($("#Role_Level"),$("#Role_Level").val());
        SetSelectSelected($("#Role_type"),$("#Role_type").val());
        formatCustomerAction($('#validForm'),'Role_note','CustomerAction');
        //$("#events-result").text('Selected values: ' + JSON.stringify($('#validForm').serializeArray()));

        //objFormatReadonly($('#validForm'),['TransCode','TransName','Imgname','ChildRadio','AreaCheck']);
        $("#modal-btn-del").removeClass('hidden');
        $("#modal-btn-save").addClass('hidden');
        $('#modal-DataEdit').modal('show');
    });
    //保存按钮
    $('#btn-DataSave').on("click",function () {
        //$("#events-result").text('Selected values: ' + $('#validForm').serialize());
        var Role_id = $('#table').bootstrapTable('getSelections')[0].Role_id;
        var dataSelected = $("#table1").bootstrapTable('getData');
        var new_pmenu = formatSelectedData(dataSelected);

        $.ajax({
            data:$('#validForm').serializeArray(),
            type: "get",
            url: globalUrl+"api/Role"+"?Role_id="+Role_id+"&new_pmenu="+new_pmenu+"",
            dataType: "json",
            success: function (resp) {
                if(resp.result)
                {
                    //$("#events-result").text('Save data ok');
                    alert("角色菜单保存成功");
                }
                else
                {
                    alert(resp.msg);
                }
            },
            error:function(){
                alert("保存数据失败！");
            }
        });
    });

    ///弹出层事件/////////////////////////////////////////////////////
    //弹出层关闭时重置valid域
    $('#modal-DataEdit').on("hide.bs.modal",function () {
        $('#validForm').data('formValidation').resetForm();
    });

    $('#modal-btn-save').on("click",function () {
        //$("#events-result").text('Selected values: ' + JSON.stringify($('#validForm').serializeArray()));
        //formValid();
    });
    $('#modal-btn-del').on("click",function () {
        //$("#events-result").text('Selected values: ' + $('#validForm').serialize());
        $.ajax({
            data:$('#validForm').serializeArray(),
            type: "delete",
            url: globalUrl+"api/Role",
            dataType: "json",
            success: function (resp) {
                if(resp.result)
                {
                    //$("#events-result").text('Send data: ' + $('#validForm').serialize());
                    dataDelFromTable($('#table'));
                    removeRoleSelected();
                    //关闭弹出窗口
                    $('#modal-DataEdit').modal('hide');
                }
                else
                {
                    alert(resp.msg);
                }
            },
            error:function(){
                alert("更新数据失败！");
            }
        });
    });
    //弹出层关闭按钮事件
    $('#modal-btn-close').on("click",function () {
    });


    ///
    function formatSelectedData(data){
        var _data = "0";
        //alert(JSON.stringify(data));
        for(var i=0;i<data.length;i++){
            if(data[i].state){
                _data = _data + ',' + data[i].Mpi_id;
                //_data = _data + ',' + data[i].Mpi_id;
            }
        }
        return _data;
    }


    ///加载角色菜单选中状态
    function loadRoleSelected(Role_id){
        $.ajax({
            data:"",
            type: "get",
            url: globalUrl+"api/Role?Role_id="+Role_id,
            dataType: "json",
            success: function (resp) {
                if(resp.result)
                {
                    refreshRoleSelected(resp.data.rows);
                }
                else
                {
                    alert(resp.msg);
                }
            },
            error:function(){
                alert("获取机构数据失败！");
            }
        });
    }

    //同步角色菜单选中状态
    function refreshRoleSelected(dataObj) {
        var rows = $("#table1").bootstrapTable('getData');
        for(var i=0;i<rows.length;i++){
            _row = rows[i];
            Mpi_id = _row.Mpi_id;
            var hasMpi = false;

            for(var j=0;j<dataObj.length;j++){
                _obj = dataObj[j];
                if(_obj.Rm_mpiid==Mpi_id){
                    hasMpi = true;
                    break;
                }
            }

            _row.state = hasMpi;
        }
        $("#table1").bootstrapTable('load', rows);
    }

    //清除角色菜单选中状态
    function removeRoleSelected() {
        var rows = $("#table1").bootstrapTable('getData');
        for(var i=0;i<rows.length;i++){
            row = rows[i];
            row.state = false;
        }
        $("#table1").bootstrapTable('load', rows);
    }


    ///复选框树形选中效果
    function refreshCheckSelected (row) {
        obj = $("#table1").find(" tbody tr ");
        parentId = row._id;
        parentPId = row._pid;
        parentState = row.state;
        state = false;

        obj.each(function(){
            ///选中儿子
            _obj = $(this);
            var _id = _obj.attr("id");
            var _pid = _obj.attr("pid");
            if( parentId == _pid ){
                var _index = _id;
                var _row = $("#table1").bootstrapTable('getData')[_index];
                _row.state = parentState;
                $("#table1").bootstrapTable('updateRow', {
                    index: _index,
                    row: _row
                });
            }

            ///选中父亲前检查儿子
            if( parentPId == _pid ){
                var _index = _id;
                var _row = $("#table1").bootstrapTable('getData')[_index];
                _state = (_row.state==undefined || _row.state==false )? false : true;
                state = state || _state;
            }
        });

        ///选中父亲
        var _index = parentPId;
        var _row = $("#table1").bootstrapTable('getData')[_index];
        _row.state = state;
        $("#table1").bootstrapTable('updateRow', {
            index: _index,
            row: _row
        });
    }

    $('#validForm input[name="CustomerAction"]').on("change",function () {
        checkCustomerAction($('#validForm input[name="Role_note"]'),$('#validForm input[name="CustomerAction"]'));
    });
    function checkCustomerAction(_input,_check){
        var _valueAreaMask = {};
        _check.each(function(){
            //_valueAreaMask += ($(this).prop("checked")) ? $(this).val()+"," : "";
            _valueAreaMask[$(this).val()] = ($(this).prop("checked")) ? true : false;
        });
        _input.val(JSON.stringify(_valueAreaMask));
    }

    function formatCustomerAction(_form,_input,_check){
        if(_form.find(' input[name="'+_input+'"] ').val() != ""){
            _obj = JSON.parse(_form.find(' input[name="'+_input+'"] ').val());
            _form.find(' input[name="'+_check+'"] ').each(function(){
                _name = $(this).val();
                _value = _obj[_name];
                $(this).prop("checked",_value);
            });
        }else{
            _form.find(' input[name="'+_check+'"] ').each(function(){
                $(this).prop("checked",false);
            });
        }

    }
</script>